from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView

from demo.models import Stu,Tea
from demo.serializers import StuSerializer,TeaSerializer


# Create your views here.



class StuRCView(View):
    def get(self,request):
        stu = Stu.objects.all()

        current_page_num=request.GET.get('number')
        per_page_nums=request.GET.get('page')

        # 分页器
        from django.core.paginator import Paginator
        stu_pa = Paginator(stu,per_page_nums)

        #总页数
        total_nums = stu_pa.num_pages

        #当前显示的数据
        stu_page = stu_pa.get_page(current_page_num)


        stu_ser = StuSerializer(instance=stu_page,many=True)

        return JsonResponse({"stu":stu_ser.data,"total_nums":total_nums},safe=False)
        # return Response(stu_ser.data)

    def post(self,request):
        stu = request.data
        stu_ser = StuSerializer(data=stu)
        stu_ser.is_valid(raise_exception=True)
        stu_ser.save()
        return JsonResponse({"list":stu_ser.data})
class StuRUDView(View):
    def get(self,request,id):
        stu = Stu.objects.get(id=id)
        stu_ser = StuSerializer(instance=stu)
        return JsonResponse({"list":stu_ser.data})
    def put(self,request,id):
        stus = request.data
        try:
            stu = Stu.objects.get(id=id)
        except:
            return JsonResponse({"没有该本图书"},status=404)
        stu_ser = StuSerializer(instance=stu,data=stus)
        stu_ser.is_valid(raise_exception=True)
        stu_ser.save()
        return JsonResponse({"修改成功"},status=201)
    def delete(self,request,id):
        try:
            stu = Stu.objects.get(id=id)
        except:
            return JsonResponse({"没有该本图书"})
        stu.delete()
        # stu.save()
        return JsonResponse({"删除成功"},status=204)
